/**
 * storage 类
 */
import { server_request } from "./request";

let storage_list = {};


export function session_storage( key, config){
    let out_time = config.outTime ? config.outTime : 1800000;

    return new Promise( (resolve, reject)=>{
        var data = sessionStorage.getItem( key);
        var data_out_time = sessionStorage.getItem( key + "_out_time");

        // 如果已经有值了，则直接返回
        if( config.value){
            resolve( config.value);
        }else if( data && Date.now() - data_out_time < out_time){
            resolve( JSON.parse( data));

        }else{

            if( !storage_list[ key]){
                storage_list[ key] = {
                    loaded : false,
                    promise_list: [],
                };
            }

            let cache = storage_list[ key];

            if( config.ajax_url ){

                if( cache.loaded ){
                    cache.promise_list.push( {
                        resolve,
                        reject,
                    });

                }else{

                    cache.loaded = true;
                    server_request( config.ajax_url ).then( (res) => {
                        // 防止反复调用接口
                        cache.loaded = false;

                        cache.promise_list.push( {
                            resolve,
                            reject,
                        });

                        if( res.code == 200){
                            sessionStorage.setItem( key, JSON.stringify( res.data));
                            sessionStorage.setItem( key + "_out_time", Date.now());
                            cache.promise_list.forEach( (item) => {
                                item.resolve( res.data);
                            });
                        }else{
                            let errorMsg = config.errorMsg | "获取数据失败";
                            console.error( errorMsg, res);
                            cache.promise_list.forEach( (item) => {
                                item.reject( errorMsg, res);
                            });
                        }
                    });
                }
            }else{

                // 如果即没有在 sessionStorage 中找到数据，也没有配置ajax地址
                // 且 value中也没值，则直接返回一个 null
                resolve( null);
            }
        }
    });
}

